<template>
  <el-row>
    <p>{{ $t('pageKvm.status') }}:</p>
    <status-icon :status="serverStatusIcon"></status-icon>
    <p>{{ connectionStatus }}</p>
  </el-row>
  <el-row>
    <div id="base-container" ref="panel1" class="relative w-[609px] h-[457px]">
      <div>
        <el-icon
          :title="$t('pageSerialOverLan.brandTitle.info')"
          class="absolute right-0 cursor-pointer hover:text-gray-200"
          size="35"
          ><warning
        /></el-icon>
        <el-button-group class="mx-auto table bg-white" size="large">
          <screen-full :element="panel1" :isFullWindow="isFullWindow" />
        </el-button-group>
      </div>

      <div
        id="terminal"
        ref="panel2"
        class="bg-[#19273c] overflow-auto h-[calc(100%-49px)]"
      />
    </div>
  </el-row>
</template>

<script setup lang="ts">
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { AttachAddon } from '@xterm/addon-attach';

import { Warning as warning } from '@element-plus/icons-vue';
import { useGlobalStore } from '@/store/global';
import { useI18n } from 'vue-i18n';
import screenFull from '@/components/global/ScreenFull.vue';
import { useAuthenticationStore } from '@/store/Authentication/Authentication';
import _ from 'lodash';
import wsUrl from '@/utilities/wsUrlTool';

const authenticationStore = useAuthenticationStore();
const i18n = useI18n();
const globalStore = useGlobalStore();

const isFullWindow = ref(false);
const panel1 = ref();
const panel2 = ref();

let resizeConsoleWindow = () => {};
const ws = ref();

onMounted(() => {
  setTimeout(() => {
    openTerminal();
    if ((navigator as any).keyboard && (navigator as any).keyboard.lock) {
      (navigator as any).keyboard.lock();
    } else {
      console.log('Your browser Not support!!!');
    }
  }, 300);
});

const openTerminal = () => {
  const token = authenticationStore.token;

  ws.value = new WebSocket(wsUrl(`wss://${window.location.host}/console0`), [
    token as string,
  ]);
  // Refer https://github.com/xtermjs/xterm.js/ for xterm implementation and addons.

  const term = new Terminal({
    fontSize: 15,
    fontFamily:
      'SFMono-Regular, Menlo, Monaco, Consolas, Liberation Mono, Courier New, monospace',
  });
  const attachAddon = new AttachAddon(ws.value);
  term.loadAddon(attachAddon);

  const fitAddon = new FitAddon();
  term.loadAddon(fitAddon);

  const SOL_THEME = {
    background: '#19273c',
    cursor: 'rgba(83, 146, 255, .5)',
    scrollbar: 'rgba(83, 146, 255, .5)',
  };
  term.options.theme = { ...SOL_THEME };

  term.open(panel2.value);
  fitAddon.fit();

  resizeConsoleWindow = _.throttle(() => {
    fitAddon.fit();
  }, 100);
  window.addEventListener('resize', resizeConsoleWindow);

  try {
    ws.value.onopen = function () {
      console.log('websocket console0/ opened');
    };
    ws.value.onclose = function (event: { code: string; reason: string }) {
      console.log(
        'websocket console0/ closed. code: ' +
          event.code +
          ' reason: ' +
          event.reason,
      );
    };
  } catch (error) {
    console.log(error);
  }
};

provide('setIsFullWindow', (status: boolean) => {
  isFullWindow.value = status;
});

const serverStatus = computed(() => globalStore.serverStatus);
const serverStatusIcon = computed(() =>
  serverStatus.value === 'on' ? 'success' : 'danger',
);

const connectionStatus = computed(() =>
  serverStatus.value === 'on'
    ? i18n.t('pageSerialOverLan.connected')
    : i18n.t('pageSerialOverLan.disconnected'),
);

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeConsoleWindow);
});

watch(isFullWindow, () => {
  resizeConsoleWindow();
});
</script>

<style lang="scss" scopped>
@import '@xterm/xterm/css/xterm.css';
</style>
